package offer;

import java.util.HashSet;
import java.util.Set;

/**
 * 剑指 Offer 03. 数组中重复的数字
 */
public class FindRepeatNumber {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 4, 5, 3, 5, 6, 7};
        int repeatNumber = findRepeatNumber1(arr);
        System.out.println(repeatNumber);
    }

    /**
     * 使用哈希表/Set
     *
     * @param arr
     * @return
     */

    public static int findRepeatNumber1(int[] arr) {
        Set<Integer> dic = new HashSet<>();
        for (int num : arr) {
            if (dic.contains(num)) return num;
            dic.add(num);
        }
        return -1;
    }

    /**
     * 原地交换
     *
     * @param arr
     * @return
     */
    private static int findRepeatNumber2(int[] arr) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        for (int i = 0; i < arr.length; i++) {
            int curr = arr[i];
            if (i != arr[i]) {
                if (arr[i] == arr[arr[i]]) {
                    return arr[i];
                }
                curr = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = curr;
                if (i != arr[i]) {
                    i--;
                }
            }
        }
        return -1;
    }

    /**
     * 使用while循环实现
     */

    private static int findRepeatNumber3(int[] arr) {
        int i = 0;
        while (i < arr.length) {
            if (i == arr[i]) {
                i++;
                continue;
            }
            if (arr[i] == arr[arr[i]]) {
                return arr[i];
            }
            int temp = arr[arr[i]];
            arr[arr[i]] = arr[i];
            arr[i] = temp;
        }
        return -1;
    }

}
